#include "StorageManager.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <cstring> 
void testBasicOperations()
{
    std::cout << "=== 测试基本操作 ===" << std::endl;

    MiniDB::StorageManager sm(10, MiniDB::ReplacementPolicy::LRU);

    // 创建表
    sm.createTable("users");
    sm.createTable("products");

    // 插入记录
    for (int i = 1; i <= 5; ++i)
    {
        MiniDB::Record record(i, "User data " + std::to_string(i));
        sm.insertRecord("users", record);
    }

    for (int i = 1; i <= 3; ++i)
    {
        MiniDB::Record record(i, "Product data " + std::to_string(i));
        sm.insertRecord("products", record);
    }

    // 查询记录
    auto users = sm.getRecords("users");
    std::cout << "Users table has " << users.size() << " records" << std::endl;

    auto products = sm.getRecords("products");
    std::cout << "Products table has " << products.size() << " records" << std::endl;

    // 打印表信息
    sm.printTableInfo("users");
    sm.printTableInfo("products");

    // 删除记录
    sm.deleteRecord("users", 3);
    std::cout << "After deletion, users table has " << sm.getRecordCount("users") << " records" << std::endl;
}

void testCachePerformance()
{
    std::cout << "\n=== 测试缓存性能 ===" << std::endl;

    MiniDB::StorageManager sm(5, MiniDB::ReplacementPolicy::LRU);

    sm.createTable("test_cache");

    // 重置统计信息
    sm.resetCacheStats();

    // 模拟缓存访问模式
    std::cout << "Performing cache access pattern..." << std::endl;

    // 访问一些页面
    for (int i = 0; i < 20; ++i)
    {
        int page_id = (i % 8) + 1; // 重复访问页面1-8
        auto page = sm.getPage(page_id);
        if (page)
        {
            sm.releasePage(page_id);
        }
    }

    // 显示缓存统计
    const auto &stats = sm.getCacheStats();
    stats.print();

    std::cout << "\nSwitching to FIFO policy..." << std::endl;
    sm.setReplacementPolicy(MiniDB::ReplacementPolicy::FIFO);
    sm.resetCacheStats();

    // 再次测试
    for (int i = 0; i < 15; ++i)
    {
        int page_id = i % 10 + 1;
        auto page = sm.getPage(page_id);
        if (page)
        {
            sm.releasePage(page_id);
        }
    }

    const auto &fifo_stats = sm.getCacheStats();
    fifo_stats.print();
}

void testPageOperations()
{
    std::cout << "\n=== 测试页操作 ===" << std::endl;

    MiniDB::StorageManager sm(10, MiniDB::ReplacementPolicy::LRU);

    // 测试直接页操作
    auto page = sm.getPage(1);
    if (page)
    {
        std::cout << "Got page 1, type: " << (page->getPageType() == MiniDB::PageType::DATA_PAGE ? "DATA" : "INDEX") << std::endl;
        std::cout << "Page size: " << MiniDB::PAGE_SIZE << " bytes" << std::endl;
        std::cout << "Free space: " << page->getFreeSpace() << " bytes" << std::endl;

        // 写入一些数据
        const char *test_data = "Hello, Page System!";
        page->writeData(0, test_data, strlen(test_data) + 1);
        std::cout << "Wrote data to page, used space: " << page->getUsedSpace() << " bytes" << std::endl;

        // 读取数据
        char buffer[256];
        page->readData(0, buffer, strlen(test_data) + 1);
        std::cout << "Read data: " << buffer << std::endl;

        sm.releasePage(1);
    }
}

void testBufferManagement()
{
    std::cout << "\n=== 测试缓冲区管理 ===" << std::endl;

    MiniDB::StorageManager sm(3, MiniDB::ReplacementPolicy::LRU); // 只有3个缓冲帧

    std::cout << "Buffer size: " << sm.getCacheStats().total_requests << std::endl;

    // 访问多个页面，触发替换
    for (int i = 1; i <= 10; ++i)
    {
        std::cout << "Accessing page " << i << std::endl;
        auto page = sm.getPage(i);
        if (page)
        {
            // 模拟一些工作
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
            sm.releasePage(i);
        }
    }

    const auto &stats = sm.getCacheStats();
    std::cout << "Final cache stats:" << std::endl;
    stats.print();

    // 调整缓冲区大小
    std::cout << "\nResizing buffer to 5 frames..." << std::endl;
    sm.resizeBuffer(5);

    // 再次测试
    sm.resetCacheStats();
    for (int i = 1; i <= 8; ++i)
    {
        auto page = sm.getPage(i % 5 + 1);
        if (page)
            sm.releasePage(i % 5 + 1);
    }

    const auto &new_stats = sm.getCacheStats();
    new_stats.print();
}

int main()
{
    std::cout << "🚀 小型数据库系统 - 页式存储系统测试" << std::endl;
    std::cout << "==========================================" << std::endl;

    try
    {
        testBasicOperations();
        testPageOperations();
        testCachePerformance();
        testBufferManagement();

        std::cout << "\n==========================================" << std::endl;
        std::cout << "✅ 所有测试完成！" << std::endl;
    }
    catch (const std::exception &e)
    {
        std::cerr << "❌ 测试失败: " << e.what() << std::endl;
        return 1;
    }

    return 0;
}
